package com.mic.handler;

import com.alibaba.fastjson2.JSON;
import com.mic.entity.AjaxResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 * 
 * @author ruoyi
 */
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {
        //同时兼容本地授权页面和获取token失败异常提示
        if("/oauth2/authorize".equals(request.getRequestURI())){
            response.sendRedirect("/login");
        }else if("/oauth2/token".equals(request.getRequestURI())){
            int code = HttpStatus.UNAUTHORIZED.value();
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(JSON.toJSONString(AjaxResult.error(code, "请求访问：" + request.getRequestURI() + "，认证失败，" + e.getMessage())));
        }
    }
}
